import os
import re
import sys

from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.management.base import BaseCommand
from django import forms

from product.models import Product, ProductImage

class ProductImageForm(forms.ModelForm):
    class Meta:
        model = ProductImage

class Command(BaseCommand):
    args = 'path'

    def handle(self, path=None, **options):

        verbosity = int(options.get('verbosity', 1))

        if not path:
            sys.stderr.write(self.style.ERROR("Path is not specified.\n"))
            return

        if not os.path.exists(path):
            sys.stderr.write(self.style.ERROR("'%s' is not exist.\n" % path))
            return

        if not os.path.isdir(path):
            sys.stderr.write(self.style.ERROR("'%s' is not a directory.\n" % path))
            return

        uploaded_sku = {}

        for file_name in sorted(os.listdir(path)):
            sku, ext = os.path.splitext(file_name)
            if ext.lower() in ['.jpg', '.jpeg', '.gif', '.png']:
                if verbosity > 0:
                    print "Processing %s" % file_name
                try:
                    sku = re.sub('_\d+$', '', sku)
                    product = Product.objects.get(sku=sku)
                    if sku in uploaded_sku or product.productimage_set.all().count() == 0:
                        picture = SimpleUploadedFile(file_name, file(os.path.join(path, file_name)).read())
                        form = ProductImageForm({'product': product.id, 'sort': 0}, {'picture': picture})
                        if form.is_valid():
                            form.save()
                            uploaded_sku[sku] = True
                        else:
                            for field in form.errors:
                                sys.stderr.write(self.style.ERROR(form.errors[field].as_text() + "\n"))
                    else:
                        sys.stderr.write(self.style.NOTICE("Images for product SKU '%s' was already uploaded.\n" % sku))
                except Product.DoesNotExist:
                    sys.stderr.write(self.style.ERROR("Product SKU '%s' not found.\n" % sku))

